package com.bolang.onlycode.demo.Cache;

import java.util.Map;
import java.util.concurrent.*;

public class Memorizer3<A,V>implements Computable<A,V> {
    // 得有个容器来放缓存
    private final Map<A,Future<V>> cache =new ConcurrentHashMap<A,Future<V>>();
    // 得有计算功能
    private final Computable<A,V> c;
    public Memorizer3(Computable<A,V> c){
        this.c=c;
    }
    @Override
    public V compute(A arg) throws InterruptedException {
        Future<V> f = cache.get(arg);
        if (f == null) {
            Callable<V> eval = new Callable<V>() {
                @Override
                public V call() throws Exception {
                    return c.compute(arg);
                }
            };
            FutureTask<V> ft = new FutureTask<V>(eval);
            f = ft;
            cache.put(arg, ft);
            ft.run();//在这里将调用c.compute
        }
        try {
            return f.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}
